#include<iostream>
#include<string>
#include"comm.hpp"
#include"mysql.h"
bool InsertSql(std::string sql,std::string sql_name)
{
    MYSQL *conn = mysql_init(nullptr);
    mysql_set_character_set(conn, "utf8");
    if(nullptr == mysql_real_connect(conn, "127.0.0.1", "http", "shuguang", "http_test", 3306, nullptr, 0)){
        std::cerr << "connect error!" << std::endl;
        return 1;
    }

    std::string s="select * from user where name=\'";
    s+=sql_name;
      s+="\'";
    std::cerr<<s<<std::endl;
    mysql_query(conn,s.c_str());
	MYSQL_RES *mr=mysql_use_result(conn);
    //打印查询结果
    MYSQL_ROW row;
		unsigned int cols = mysql_field_count(conn);
    int flag=0;
while((row=mysql_fetch_row(mr)))
    {
      flag=1;
			for(unsigned int i=0;i<cols;i++)
			{
				std::cerr<<row[i];
			}
			std::cerr<<std::endl;
    }
  if(flag==0)
  {
    std::cerr<<sql<<std::endl;
    std::cerr<<"不存在该用户,插入"<<std::endl;
    int ret1 = mysql_query(conn, sql.c_str());
    if(ret1!=0)
    {
      std::cerr<<"失败"<<std::endl;
    }
  }
  else 
  {
    std::cerr<<"存在该用户"<<std::endl;
mysql_free_result(mr);
    mysql_close(conn);
    return false;
  }

mysql_free_result(mr);
    mysql_close(conn);
    return true;
}

int main()
{
   std::string query_string;
    //from http
    if(GetQueryString(query_string)){
        std::cerr << query_string << std::endl;
        //数据处理？
        //name=tom&passwd=111111

        std::string name;
        std::string passwd;

        CutString(query_string, "&", name, passwd);

        std::string _name;
        std::string sql_name;
        CutString(name, "=", _name, sql_name);

        std::string _passwd;
        std::string sql_passwd;
        CutString(passwd, "=", _passwd, sql_passwd);

        std::string sql = "insert into user(name, password) values (\'";
        sql += sql_name;
        sql += "\',\'";
        sql += sql_passwd;
        sql += "\')";

        std::cerr<<sql_name<<"12"<<std::endl;
        //插入数据库
        if(InsertSql(sql,sql_name)){
            std::cout << "<html>";
            std::cout << "<head><meta charset=\"utf-8\"></head>";
            std::cout << "<body><h1>注册成功!</h1></body>";
        }
        else 
        {  
          std::cout << "<html>";
          std::cout << "<head><meta charset=\"utf-8\"></head>";
          std::cout << "<body><h1>该用户已存在，请重新注册</h1></body>";
        }
    }
  return 0;
}
